<template>
  <div>
    <!-- 第一行  -->
    <div class="header">
      <div class="header-container">
        <el-form :inline="true" :model="form" class="search-form">
          <el-form-item>
            <el-select clearable v-model="form.online_status" placeholder="请选择设备状态">
              <el-option label="在线" :value="1"></el-option>
              <el-option label="离线" :value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select clearable v-model="form.bind_status" placeholder="请选择设备绑定状态">
              <el-option label="未绑定" :value="0"></el-option>
              <el-option label="已绑定" :value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input clearable v-model="form.name" placeholder="请输入设备名称"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="danger" @click="toSearch">搜索</el-button>
          </el-form-item>
          <!-- 录入按钮 -->
          <div class="action-buttons">
            <el-button type="primary" @click="toAdd" >录入</el-button>
          </div>
          <!-- 录入结束 -->
        </el-form>
      </div>
    </div>

    <!-- 第二行  -->
    <div class="table">
      <el-table :data="deviceData" style="width: 100%">
        <el-table-column type="index" :index="1" label="序号" width="180">
        </el-table-column>
        <el-table-column prop="serial_number" label="编号" width="180">
        </el-table-column>
        <el-table-column prop="name" label="名称">
        </el-table-column>
        <el-table-column prop="online_status" width="180" label="设备状态">
          <template v-slot="scope">
            <div>
              <el-tag v-if="scope.row.online_status == 1" type="success">在线</el-tag>
              <el-tag v-else type="danger">离线</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="bind_status" width="180" label="绑定状态">
          <template v-slot="scope">
            <div>
              <el-tag v-if="scope.row.bind_status == 1" type="success">已绑定</el-tag>
              <el-tag v-else type="danger">未绑定</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column width="180" label="操作">
          <template v-slot="scope">
            <div>
              <el-link type="success" @click="toEdit(scope.row)">修改</el-link>
              <el-link type="danger" @click="toDelete(scope.row.id)">删除</el-link>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 抽屉 -->
    <el-drawer size="50%" :title="title" :visible.sync="visible" direction="rtl" custom-class="demo-drawer"
      ref="drawer">
      <div class="demo-drawer__content" style="padding-right: 10px;">
        <!-- 添加表单校验相关属性 -->
        <el-form :model="formSave" :rules="rules" ref="myForm" label-width="100px">
          <el-row>
            <el-col :span="60">
              <el-form-item prop="serial_number" label="编号">
                <el-input class="input" clearable placeholder="请输入编号" v-model="formSave.serial_number"
                  autocomplete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="60">
              <el-form-item prop="name" label="名称">
                <el-input class="input" clearable placeholder="请输入名称" v-model="formSave.name"
                  autocomplete="off"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row style="margin-top: 20px; text-align: right;">
            <div class="demo-drawer__footer">
              <el-button @click="visible = false">取消</el-button>
              <el-button type="primary" @click="submitForm">提交</el-button>
            </div>
          </el-row>
        </el-form>
      </div>
    </el-drawer>

  </div>
</template>
<script>
import { get, post, del} from '@/utils/request'
import _ from 'lodash'

export default {
  data() {
    return {
      // 提供表单数据对象 --->条件对象 
      form: {},
      // 设备数据 
      deviceData: [],
      params: {
        page: 1,
        pageSize: 10
      },
      // 抽屉标题 
      title: '录入设备信息',
      // 控制抽屉显示与隐藏 
      visible: false,
      // 录入和修改表单数据对象 - 初始化具体属性
      formSave: {
        serial_number: '',
        name: ''
      },
      // 表单标签域宽度 
      formLabelWidth: '100px',
      // 表单验证规则 
      rules: {
        serial_number: [
          { required: true, message: '请输入编号', trigger: "blur" },
        ],
        name: [
          { required: true, message: '请输入名称', trigger: "blur" },
        ],
      }
    }
  },
  methods: {
    // 从第一页开始查
    toSearch() {
      this.params.page = 1;
      this.getDevData();
    },
    // 修改设备信息 - 修复连续修改问题
    toEdit(row) {
      // 先重置表单状态
      if (this.$refs['myForm']) {
        this.$refs['myForm'].resetFields();
      }
      // 更新标题
      this.title = "修改设备信息";
      // 深拷贝当前行数据，避免引用问题
      this.formSave = _.cloneDeep(row);
      // 确保抽屉显示
      this.visible = true;
    },
    // 提交表单
    submitForm() {
      this.$refs['myForm'].validate(async (valid) => {
        if (valid) {
          try {
            // 表单校验通过  发起保存或者更新请求
            let data = _.clone(this.formSave);
            let url = '/device/saveOrUpdate';
            // 修复原代码中引用不存在的address1问题
            // 如果确实需要地址处理，请补充完整相关逻辑
            // 如果有id，说明是修改操作  id变换判断时候有修改
            if (data.id) {
              url = '/device/update'; // 假设修改接口为/device/update
            }
            let res = await post(url, data); // 修改为设备相关接口S
            if (res.status == 200) {
              this.$notify({
                title: "成功",
                message: res.message || '操作成功',
                type: 'success'
              });
              this.visible = false;
              // 重新查询数据
              this.getDevData(); // 修复方法名错误
            }
          } catch (error) {
            console.error('提交失败:', error);
            this.$notify({
              title: "错误",
              message: '提交失败，请重试',
              type: 'error'
            });
          }
        } else {
          // 表单校验失败
          console.log('表单校验失败');
          return false;
        }
      });
    },
    // 去删除工程 
    toDelete(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 点了确定按钮 发起删除工程请求 
        let res = await del('/device/deleteById', { id });
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
        // 从第一页重新载入数据 
        this.params.page = 1;
        // 重新载入数据 
        this.getEngData();
      });
    },
    // 结束工程 
    toFinish(id) {
      // console.log(id);
      this.$confirm('此操作将永久结束该工程, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 点了确定按钮 发起结束工程请求 
        let res = await get('/device/deleteById', { id });
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
        // 重新载入数据 
        this.getDevData();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 获取设备数据方法 
    async getDevData() {
      try {
        let temp = {
          ...this.form,
          ...this.params
        };
        let res = await get('/device/pageQuery', temp);
        console.log(res, '获取设备响应');
        if (res.status === 200) {
          this.deviceData = res.data?.list || [];
        }
      } catch (error) {
        console.error('获取设备数据失败:', error);
      }
    },
    // 录入设备信息 
    toAdd() {
      // 抽屉显示
      this.visible = true;
      // 修改标题 
      this.title = "录入设备信息";
      // 清空表单数据对象并初始化属性
      this.formSave = {
        serial_number: '',
        name: ''
      };
      // 重置表单验证状态
      this.$nextTick(() => {
        if (this.$refs['myForm']) {
          this.$refs['myForm'].resetFields();
        }
      });
    },
  },
  created() {
    this.getDevData();
  }

}
</script>
<style lang="scss" scoped>
::v-deep .el-link--inner {
  margin-left: 5px;
}

// 整体页面内边距
.header {
  padding: 15px;
  margin-bottom: 0; // 移除底部外边距
}

.table {
  margin-top: 0; // 移除顶部外边距
  border: 1px solid #EBEEF5; // 添加边框，与搜索区视觉连接

  ::v-deep .el-table__header-wrapper {
    border-bottom: 1px solid #EBEEF5;
  }
}
// 搜索表单样式
.search-form {
  display: flex;
  align-items: center;
  ::v-deep .el-form-item {
    margin-right: 10px;
    margin-bottom: 0; // 消除底部间距，确保垂直对齐
  }
}
.action-buttons {
  margin-left: 300px;  // 与搜索区域保持一定距离
}
.input {
  width: 100%;
}
</style>
